//
//  FileCtrlDemo.m
//  FileManageDemo
//
//  Created by shk on 14/12/2.
//  Copyright (c) 2014年 com.shk. All rights reserved.
//

#import "FileCtrlDemo.h"

@implementation FileCtrlDemo






/**
 * 向文件中追加内容
 */
- (void) appendFile{
     NSString *homePath = NSHomeDirectory();//用户根目录
     NSLog(@"当前用户的目录：%@", homePath);
     NSString *filePath = [homePath stringByAppendingPathComponent:@"temp/oc-file-test.txt"];
     NSLog(@"指定文件的路径：%@", filePath);
     NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
     NSLog(@"%@", fileHandle);
     if(fileHandle != nil){
     [fileHandle seekToEndOfFile];
     //[fileHandle seekToFileOffset:10];//跳转到指定的偏移量，从指定偏移量开始写，新数据会覆盖原来同位置的数据
     NSString *str = @"追加数据";
     NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
     [fileHandle writeData:data];
     }else{
     NSLog(@"指定的文件不存在！");
     }
     [fileHandle closeFile];
}


/**
 * 从指定位置读取文件内容
 */
- (void) readFile{
    
     NSString *homePath = NSHomeDirectory();//用户根目录
     NSString *filePath = [homePath stringByAppendingPathComponent:@"temp/oc-file-test.txt"];
     NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
     NSLog(@"%@", fileHandle);
     if(fileHandle != nil){
     NSUInteger length = [fileHandle availableData].length;
     NSLog(@"文件内容的长度：%lu", (unsigned long)length);
     [fileHandle seekToFileOffset:length/2];
     NSData *data = [fileHandle readDataToEndOfFile];
     NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
     NSLog(@"读取的内容：%@", str);
     }else{
     NSLog(@"指定的文件不存在！");
     }
}



/**
 * 从指定位置读取文件内容
 */
- (void) copyFile{
    NSString *homePath = NSHomeDirectory();//用户根目录
    NSString *filePath = [homePath stringByAppendingPathComponent:@"temp/oc-file-test.txt"];
    NSString *targetFilePath = [homePath stringByAppendingPathComponent:@"temp/oc-file-test-copy.txt"];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL success = [fileManager createFileAtPath:targetFilePath contents:nil attributes:nil];
    if(success){
        NSLog(@"文件创建成功！");
        NSFileHandle *outFileHandle = [NSFileHandle fileHandleForWritingAtPath:targetFilePath];
        NSFileHandle *inFileHandle = [NSFileHandle fileHandleForReadingAtPath:filePath];
        
        NSData *data = [inFileHandle readDataToEndOfFile];
        [outFileHandle writeData:data];
        
        [outFileHandle closeFile];
        [inFileHandle closeFile];
        
    }else{
        NSLog(@"文件创建失败！");
    }
}




@end
